﻿using System;
using System.Reflection;
using System.Windows.Forms;

namespace CssCommonLibrary
{
    public class CssCheckList : CheckedListBox
    {
        protected override void OnDataSourceChanged(EventArgs e)
        {
            try
            {
                base.OnDataSourceChanged(e);
            }
            catch { }
        }

        protected override void OnItemCheck(ItemCheckEventArgs args)
        {
            BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            EventInfo eventInfo = this.GetType().GetEvent("ItemCheck", bindingFlags);
            FieldInfo fi = this.GetType().BaseType.GetField("onItemCheck", bindingFlags);
            Delegate method = fi.GetValue(this) as Delegate;

            if (method != null)
            {
                eventInfo.RemoveEventHandler(this, method);
                if (this.GetItemChecked(args.Index))
                    this.SetItemChecked(args.Index, false);
                else
                    this.SetItemChecked(args.Index, true);
                eventInfo.AddEventHandler(this, method);
            }
            else
            {
                return;
            }
            base.OnItemCheck(args);
        }

        public CssNodeList CheckedNodes
        {
            get
            {
                CssNodeList list = new CssNodeList();
                foreach (var item in this.CheckedItems)
                {
                    list.Add(item as CssClassNode);
                }
                return list;
            }
        }

        public CssNodeList InitialDataSource { get; set; }

        public CssCheckList() { }

        public CssCheckList(CssNodeList list)
        {
            this.InitialDataSource = list;
        }

        public void BindData(CssNodeList list)
        {
            ListBox lb = this as ListBox;
            lb.DataSource = list;
            lb.DisplayMember = "Selector";
        }

        public void BindData()
        {
            this.BindData(this.InitialDataSource);
        }

        public void Filter(string selector)
        {
            ListBox lb = this as ListBox;
            lb.DataSource = this.InitialDataSource.FindAll(t => t.Selector.ToLower().Contains(selector.ToLower()));
        }

        private void SetAllChecked(bool value)
        {
            for (int i = 0; i < this.Items.Count; i++)
            {
                this.SetItemChecked(i, value);
            }
        }
    }
}
